<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getToken } from '@/utils/webStorage'
import { useGlobalStore } from '@/stores/globalStore'
const props = defineProps({
  position: {
    type: String,
    default: 'bottom-right',
  },
  trigger: {
    type: String,
    default: 'click',
  },
  needLogin: {
    type: Boolean,
    default: false,
  },
})

const position = computed(() => {
  // 右对齐
  if (props.position === 'bottom-right') {
    return {
      'top-[calc(100%+8px)]': true,
    }
  }
  // 左对齐
  if (props.position === 'bottom-left') {
    return {
      'top-[calc(100%+8px)]': true,
      'left-0': true,
    }
  }

  if (props.position === 'bottom-center') {
    return {
      'top-[calc(100%+8px)]': true,
      'left-[50%]': true,
      'translate-x-[-50%]': true,
    }
  }

  if (props.position === 'right') {
    return {
      'left-[calc(100%+8px)]': true,
      'top-0': true,
    }
  }
})

const isShow = ref(false)
const dropdownRef = ref(null)

const timer = ref(null)

const togglePanel = () => {
  if (props.needLogin && !getToken()) {
    useGlobalStore().showLogin()
    return
  }
  isShow.value = !isShow.value
}

// 暴露隐藏面板的方法
const hidePanel = () => {
  isShow.value = false
}

const showPanelLater = () => {
  clearTimeout(timer.value)

  setTimeout(() => {
    isShow.value = true
  }, 500)
}

const hidePanelLater = () => {
  timer.value = setTimeout(() => {
    isShow.value = false
  }, 500)
}

// 鼠标在面板上时不隐藏
const handleMouseEnterPanel = () => {
  clearTimeout(timer.value)
  isShow.value = true
}

const handleMouseLeavePanel = () => {
  hidePanelLater()
}

// 添加点击外部关闭的处理函数
const handleClickOutside = (event) => {
  if (dropdownRef.value && !dropdownRef.value.contains(event.target)) {
    isShow.value = false
  }
}

// 在组件挂载时添加事件监听器，在组件卸载时移除
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 通过 defineExpose 暴露方法给父组件
defineExpose({
  hidePanel,
})
</script>

<template>
  <div ref="dropdownRef" class="relative">
    <div @click="togglePanel" v-if="trigger === 'click'">
      <slot></slot>
    </div>

    <div v-if="trigger === 'click'">
      <div class="absolute right-0 bg-[--fill-0] rounded-lg z-10 w-fit" :class="position" v-if="isShow">
        <slot name="content"></slot>
      </div>
    </div>

    <div v-if="trigger === 'hover'" @mouseenter="showPanelLater" @mouseleave="hidePanelLater">
      <slot></slot>
    </div>

    <div v-if="trigger === 'hover'">
      <div
        @mouseenter="showPanelLater"
        @mouseleave="hidePanelLater"
        class="absolute right-0 bg-[--fill-0] rounded-lg z-10 w-fit"
        :class="position"
        v-if="isShow">
        <slot name="content"></slot>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss"></style>
